"""This module provides mydouyn"""
import time
import json
import random
import os
import re
import platform
from auto.sleep.data import go_to_sleep
from auto.sleep.data import get_pitcute
import traceback
import datetime
from playwright.sync_api import sync_playwright
from playwright.sync_api import Page
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
class CMaiMaiBook:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """
    def __init__(self,cookies_path: str, login_url: str, 
                      upload_picture_url: str, upload_mp4_url: str):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.upload_picture_url = upload_picture_url
        self.upload_mp4_url = upload_mp4_url
        # playwright 部分
        self.browser = None
        self.page = None
        self.context = None
        print("create maimai")

    def __del__(self):
        print("------------------CMaiMaiBook is being destroyed-------------")

    def upload_picture(self, picture_path: str, habit_name: str, habit_detail:str):
        """
          upload_picture
        """
        with sync_playwright() as playwright:
            display_headless = False
            #display_headless = True
            sys = platform.system()
            if sys == "Linux":
                display_headless = True
            if sys == "Linux":
              self.browser = playwright.chromium.launch(headless=display_headless)
            else:
                self.browser = playwright.chromium.launch(channel="chrome",headless=display_headless)
            login_page = self.login_or_restore_cookies()
            self.msg_up_load(login_page, picture_path, habit_name, habit_detail)
            self.browser.close()
    def crate_browser_instance(self):
        """
        crate_browser_instance
        https://playwright.dev/python/docs/library
        playwright = sync_playwright().start()
        """
        playwright = sync_playwright().start()
        self.browser = playwright.chromium.launch(channel="chrome",headless=False)

        self.page = self.login_or_restore_cookies()
    def login_or_restore_cookies(self) -> Page:
        """
          登录
        """
        # https://useragent.buyaocha.com/
        #  https://http.dev/user-agent
        userAgent ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
        sys = platform.system()
        if sys == "Linux":
            userAgent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
        elif sys == "Darwin":
           # chrome://version/
           userAgent='ozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
        
        self.context = self.browser.new_context(user_agent=userAgent)
        #browser.new_context() 创建一个新的浏览器上下文。它不会与其他浏览器上下文共享 cookies/缓存。
        #context之间是相互隔离的，可以理解为轻量级的浏览器实例--打开了多个浏览器
        
        if os.path.exists(self.cookies_path):
            with open(self.cookies_path, 'r',encoding='utf-8') as f:
                cookies = json.load(f)

            current_time = datetime.datetime.now()
            # 延长1天
            extended_time = current_time + datetime.timedelta(days=1)
            # 获取时间戳（精确到秒）
            timestamp = int(extended_time.timestamp())
            print(timestamp)
            for cookie in cookies:
                 if cookie['name'] == 'access_token':
                    cookie['expires'] = timestamp
                    print(cookie)
                 if cookie['name'] == 'access_token.sig':
                    cookie['expires'] = timestamp
                    print(cookie)
                 if cookie['name'] == 'browser_fingerprint':
                    cookie['expires'] = timestamp
                    print(cookie)
                 if cookie['name'] == 'channel':
                    cookie['expires'] = timestamp
                    print(cookie)
                
                 if cookie['name'] == 'channel.sig':
                    cookie['expires'] = timestamp
                    print(cookie)
                 if cookie['name'] == 'guid':
                    cookie['expires'] = timestamp
                 if cookie['name'] == 'seid':
                    cookie['expires'] = timestamp
                 if cookie['name'] == 'session':
                    cookie['expires'] = timestamp
                 if cookie['name'] == 'session.sig':
                    cookie['expires'] = timestamp
                 if cookie['name'] == 'u' or cookie['name'] == 'u.sig':
                    cookie['expires'] = timestamp
    
            self.context.add_cookies(cookies)
            time.sleep(3)
        # 先添加add_cookies
        # 每个浏览器上下文可以承载多个页面
        # Each BrowserContext can have multiple pages. 
        # A Page refers to a single tab or a popup window within a browser context. 
        # It should be used to navigate to URLs and interact with the page content.
        page = self.context.new_page()
        page.goto(self.login_url)

        if os.path.exists(self.cookies_path):
            pass
        else:
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            time.sleep(45)
            cookies = page.context.cookies()
            with open(self.cookies_path, 'w',encoding='utf-8') as f:
                f.write(json.dumps(cookies))
        print("login_or_restore_cookies")
        return page

    def msg_up_load(self, page: Page, picture_path: str, habit_name: str, habit_detail:str):
        """
        上传图文
        """
        page.goto(self.upload_picture_url)
        page.wait_for_timeout(2000)
        print(f"open  {self.upload_picture_url}")
        # xpath使用文本内容定位元素
        page.locator("div").filter(has_text=re.compile(r"^分享职场动态（好友、同行能看到）0/650$")).locator("div").fill(habit_detail)
        print("分享职场动态（好友、同行能看到)")
        page.wait_for_timeout(2000)
        print(f"post....")
        
        # 点击选择文件，输入文件
        # <div class="imgBtn m-t-0">
        #   <input type="file" accept=".png,.jpg" multiple="" class="file-input">
        # </div>
        # https://www.cnblogs.com/yoyoketang/p/17175183.html
        with page.expect_file_chooser() as fc_info:
             page.locator("input[type=\"file\"]").click()
        file_chooser = fc_info.value
        file_chooser.set_files(picture_path)
        page.wait_for_timeout(30000)
        # 发布
        ##page.locator("xpath=//button[./span[text()='发布']]").click()
        # <div class="sendBtn" style="opacity: 1;">发布</div>
        page.locator("css=.sendBtn").click()
        print("发布")
        page.wait_for_timeout(5000)      

####################################################################3
def interface_auo_upload_msg_maimai(file_path_list:str,habit_name :str,habit_detail :str):
    """
     早睡提醒 
    """
    sys = platform.system()
    login_url = "https://maimai.cn/feed_list"
    upload_picture_url = "https://maimai.cn/feed_list"
    upload_mp4_url = "https://maimai.cn/feed_list"
    sys = platform.system()
    cookies_path = "./xiaohongshu_small.json"
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\maimai_small.json"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/mp4/etc/maimai_small.json"
    else:
        cookies_path = r"/root/bin/maimai_small.json"
    try:
        autoupload = CMaiMaiBook(cookies_path, login_url, upload_picture_url,upload_mp4_url)
        display_headless = False
        with sync_playwright() as p:
            if platform.system() == "Linux":
                display_headless = True
                autoupload.browser = p.chromium.launch(headless=display_headless)
            else:
                autoupload.browser = p.chromium.launch(channel="chrome",headless=display_headless)

            autoupload.page = autoupload.login_or_restore_cookies()
            autoupload.msg_up_load(autoupload.page,file_path_list, habit_name, habit_detail)
            autoupload.browser.close()
    except Exception as err:
        print(f">>>>>>>>>>Unexpected {err=}, {type(err)=}")

#############################################
def future_for_sleep():
    """
      每天写50字产品理解输出，10行代码
    """
    habit_detail = go_to_sleep.interface_go_to_sleep()
    random_images = get_pitcute.interface_get_three_pic()
    habit_name = "21点远离手机提醒"
    # 格式化为 年-月-日
    formatted_date = datetime.datetime.now().strftime('%Y-%m-%d')
    habit_name = formatted_date + " " + habit_name

    try:
        interface_auo_upload_msg_maimai(random_images, habit_name, habit_detail)
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
#####################
def interface_not_quit_auto_mm_window():
    """
     早睡提醒 
    """
    sys = platform.system()
    login_url = "https://maimai.cn/feed_list"
    upload_picture_url = "https://maimai.cn/feed_list"
    upload_mp4_url = "https://maimai.cn/feed_list"
    sys = platform.system()
    cookies_path = "./xiaohongshu_small.json"
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\maimai_small.json"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/mp4/etc/maimai_small.json"
    else:
        cookies_path = r"/root/bin/maimai_small.json"
  
    try:
        autoupload = CMaiMaiBook(cookies_path, login_url, upload_picture_url,upload_mp4_url)
        autoupload.crate_browser_instance()
        print("--------------start shipinhao----------------")
        while True:
            # 发布图文
            habit_detail = go_to_sleep.interface_go_to_sleep()
            file_path_list = get_pitcute.interface_get_three_pic()
            habit_name = "21点远离手机提醒"
            # 格式化为 年-月-日
            formatted_date = datetime.datetime.now().strftime('%Y-%m-%d')
            temp = formatted_date + " " + habit_name
            habit_detail = temp + "\r\n" + habit_detail
            autoupload.msg_up_load(autoupload.page,file_path_list, habit_name, habit_detail)
            #steps = 100
            steps = 10*60*60*1000
            autoupload.page.wait_for_timeout(steps)
            print("--------------start shipinhao----------------")
    finally:
        autoupload.browser.close()
if __name__ == '__main__':
    # playwright codegen  https://maimai.cn/web/feed_explore 
    interface_not_quit_auto_mm_window()
    # future_for_sleep()
    # job_defaults = {
    #     'coalesce': False,
    #     'max_instances': 1
    # }
    # # 调度器组件
    # backsched = BlockingScheduler(job_defaults=job_defaults, timezone='Asia/Shanghai')
    # # future_for_sleep callable函数 习惯养成--早睡早起
    # # crontab 是 Linux 系统中用于设置周期性被执行的指令的命令
    # # 0 0 * * *	每天的午夜（0 点）执行一次
    # backsched.add_job(future_for_sleep, CronTrigger.from_crontab("10 22 * * *"), id="get_up")
    # backsched.start()